import { useEffect, useState } from 'react';
import { Button, Space, Form, Row, Col, Input, Table, DatePicker, Modal } from 'antd';
import { PAGINATION_CONFIG } from '@/constants';
import type { StubLog, QueryStubLogListParams } from './services';
import { queryStubLogList } from './services'
import { useRequest } from 'ahooks';
import type { ColumnsType } from 'antd/es/table/interface';
import dayjs from 'dayjs';

const AppUserPage: React.FC<RoutePageProps> = (props) => {
  const [searchForm] = Form.useForm()
  const [searchParams, setSearchParams] = useState<QueryStubLogListParams>({
    pageNum: 1, pageSize: 10, 
    beginDay: dayjs().subtract(30, 'days').format('YYYYMMDD'),
    endDay: dayjs().format('YYYYMMDD'),
  })
  const list = useRequest(() => queryStubLogList(searchParams), {
    ready: !!searchParams.stubId,
    refreshDeps: [searchParams],
    onSuccess: (res) => {
      if (res.data.length === searchParams.pageSize) {
        list.mutate({
          ...res,
          totalCount: searchParams.pageNum * searchParams.pageSize + 1
        })
      }
    }
  })

  const onFinish = (formValues: any) => {
    const startMonth = formValues.dayRange?.[0].format('YYYYMM')
    const endMonth = formValues.dayRange?.[1].format('YYYYMM')
    if (startMonth !== endMonth) {
      Modal.warn({
        title: '提示',
        content: '查询时间不可跨月选择',
      })
      return
    }
    setSearchParams({
      ...searchParams,
      beginDay: formValues.dayRange?.[0]?.format('YYYYMMDD'),
      endDay: formValues.dayRange?.[1]?.format('YYYYMMDD'),
      stubId: formValues.stubId,
      pageNum: 1,
    })
  }

  const columns: ColumnsType<StubLog> = [
    {
      title: '状态码',
      dataIndex: 'statusCode',
      width: 120,
      render: val => val || '--'
    },
    {
      title: '上报时间',
      dataIndex: 'time',
      width: 240,
    },
    {
      title: '状态描述',
      dataIndex: 'statusName',
      width: 240,
    },
  ]

  useEffect(() => {
    if (props.params.stubId) {
      const values = {
        ...searchForm.getFieldsValue(),
        stubId: props.params.stubId,
      }
      searchForm.setFieldsValue(values)
      onFinish(values)
    }
  }, [props.params.stubId])
  
  return (
    <div className='container'>
      <div className="card search-card">
        <div className="form-area">
          <Form
            name='searchErrorForm' form={searchForm} 
            onFinish={onFinish}
            initialValues={{dayRange: [dayjs().startOf('month'), dayjs()]}}
          >
            <Row gutter={[20, 20]}>
              <Col span={6}>
                <Form.Item label='设备编号' name='stubId' rules={[{required: true, message: '请输入设备编号'}]}>
                  <Input placeholder='请输入' />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Form.Item label='上报日期' name='dayRange'>
                  <DatePicker.RangePicker style={{width: '100%'}} allowClear={false} disabledDate={current => current.isAfter(dayjs(), 'day')} />
                </Form.Item>
              </Col>
              <Col span={6}>
                <Space>
                  <Button type='primary' htmlType='submit' loading={list.loading}>筛选</Button>
                  <Button htmlType='reset'>重置</Button>
                </Space>
              </Col>
            </Row>
          </Form>
        </div>
      </div>
      <div className="card content-card">
        <Table<StubLog>
          rowKey='stubId'
          loading={list.loading}
          dataSource={list.data?.data}
          columns={columns}
          scroll={{y: 700, x: 'max-content'}}
          pagination={{
            ...PAGINATION_CONFIG,
            current: searchParams.pageNum,
            pageSize: searchParams.pageSize,
            total: list.data?.totalCount || 0,
            showTotal: false,
            onChange: (page, pageSize) => {
              setSearchParams({
                ...searchParams,
                pageNum: page === searchParams.pageNum ? 1 : page,
                pageSize,
              })
            }
          }}
        />
      </div>
    </div>
  );
};

export default AppUserPage;
